//
//  WPOAuthViewController.swift
//  WB
//
//  Created by 汪鹏 on 2016/12/28.
//  Copyright © 2016年 汪鹏. All rights reserved.
//

import UIKit
import SVProgressHUD

class WPOAuthViewController: UIViewController, UIWebViewDelegate {

    
    /// 懒加载登陆页（写法1）
    private lazy var webView:UIWebView = {
        
        let webV = UIWebView()
        
        webV.delegate = self
        
        return webV
        
        }()
    
    /// 懒加载登陆页（写法2）
    //private lazy var webView:UIWebView = UIWebView()
    
    override func loadView() {
        
        // 替换控制器的根视图
        view = webView

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //webView.delegate = self
        
        view.backgroundColor = UIColor.white
        
        title = "微博用户登陆"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", fontSize: 16, target: self, action: #selector(goBack), isBack: true)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: 16, target: self, action: #selector(zidongtianzhong), isBack: false)
        
        // 加载新浪的登陆页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APP_KEY)&redirect_uri=\(APP_REDIRECTURL)"
        
        guard let url = URL(string: urlString)else{
            
            print("加载登陆页的路径为空")
            
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)

    }
    
    @objc private func goBack(){
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func zidongtianzhong(){
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='15555765796'")
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('passwd').value='monica1314'")
    }
   
    
    // MARK:--UIWebViewDelegate
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if request.url?.absoluteString.hasPrefix(APP_REDIRECTURL)  == false {
            return true
        }
        
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            
            goBack()
            
            return false
        }
        
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        WPNetManager.shareManager.loadAccessToken(code: code) { (isSuccess) in
            
            if isSuccess == true {
                
                SVProgressHUD.showInfo(withStatus: "登陆成功")
                
                // 发送登陆成功的通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: USERLOGINSUCCESSNOTIFICATION), object: nil)
                
            }else{
               
                SVProgressHUD.showInfo(withStatus: "登陆失败")
                
            }
            
            // 关闭授权页
                self.goBack()
                            
        }
        
        return false
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
}
